const express = require('express');
const router = express.Router();
const PrintJob = require('../models/printJob');
const Device = require('../models/device');

// 获取所有打印任务
router.get('/', async (req, res) => {
    try {
        const printJobs = await PrintJob.findAll({
            include: [Device]
        });
        res.json(printJobs);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// 获取单个打印任务
router.get('/:id', async (req, res) => {
    try {
        const printJob = await PrintJob.findByPk(req.params.id, {
            include: [Device]
        });
        if (!printJob) {
            return res.status(404).json({ error: '打印任务不存在' });
        }
        res.json(printJob);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// 创建打印任务
router.post('/', async (req, res) => {
    try {
        const device = await Device.findByPk(req.body.deviceId);
        if (!device) {
            return res.status(404).json({ error: '设备不存在' });
        }
        const printJob = await PrintJob.create(req.body);
        res.status(201).json(printJob);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

// 更新打印任务状态
router.put('/:id/status', async (req, res) => {
    try {
        const printJob = await PrintJob.findByPk(req.params.id);
        if (!printJob) {
            return res.status(404).json({ error: '打印任务不存在' });
        }
        await printJob.update({
            status: req.body.status,
            startTime: req.body.status === 'printing' ? new Date() : printJob.startTime,
            endTime: ['completed', 'failed'].includes(req.body.status) ? new Date() : printJob.endTime,
            errorMessage: req.body.errorMessage
        });
        res.json(printJob);
    } catch (error) {
        res.status(400).json({ error: error.message });
    }
});

// 获取设备的打印任务
router.get('/device/:deviceId', async (req, res) => {
    try {
        const printJobs = await PrintJob.findAll({
            where: { deviceId: req.params.deviceId },
            include: [Device]
        });
        res.json(printJobs);
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

module.exports = router; 